package com.bsj.media.init.dto;

import cn.hutool.core.io.file.FileWriter;
import com.bsj.media.media.VideoServerCmdType;
import com.bsj.media.media.self.MyselfFLVMedia2;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
public class NettyHttpDto extends NetDto {

    //缓存信息
//    private MySelfFlvMedia media = new MySelfFlvMedia(VideoServerCmdType.MEDIA, 0);

    //缓存信息
//    private MySelfFlvMedia media = new MySelfFlvMedia(VideoServerCmdType.MEDIA, 0);

//    private MyselfFLVMedia2 media = new MyselfFLVMedia2(VideoServerCmdType.MEDIA, "", 0, 1);
    private MyselfFLVMedia2 media;

    private ChannelHandlerContext channelHandlerContext;

    private boolean flag = false;

    private String fileName;

    public NettyHttpDto(ChannelHandlerContext now, String type) {
        channelHandlerContext = now;
        //需要判断是按照音视频来打包,还是纯视频来打包
        if (type.equalsIgnoreCase(VideoServerCmdType.MEDIA)) {
            media = new MyselfFLVMedia2(VideoServerCmdType.MEDIA, "", 0, 1);
        } else if (type.equalsIgnoreCase(VideoServerCmdType.VIDEO)) {
            media = new MyselfFLVMedia2(VideoServerCmdType.VIDEO, "", 0, 1);
        } else {
            //默认使用音视频打包
            media = new MyselfFLVMedia2(VideoServerCmdType.MEDIA, "", 0, 1);
        }
//        media.initNetDto(this);
    }

    public void initLiveVideo() {
//        media.liveVideo();
    }

    public void downFile(String name) {
        fileName = name;
    }

    @Override
    public void sendData(byte[] fdBody) {
        byte[] data = new byte[600 * 1024];
        if (fdBody.length > data.length) {
            log.warn("打包数据超过缓冲区： {}", fdBody.length);
            return;
        }
        int i = media.packetData(fdBody, data);
        if (fileName != null) {
            //下载
            channelDownloadDataHead(fileName);
        } else {
            if (!flag) {
                channelSendDataHead();
                flag = true;
            }
        }
        if (i > 0) {
//            if (this.getSim().equalsIgnoreCase("179")) {
//                FileWriter writer = new FileWriter("/soft/decode/" + this.getSim() + ".flv");
//                writer.write(data, 0, i, true);
//            }
//            log.info("打包大小:{}", i);
            sendDataWrite(data, i);
        }
    }

    @Override
    public boolean headFlag() {
//        return media.isPacketFlvHeader;
        return true;
    }

    @Override
    public void downloadClose() {
        if (fileName != null) {
            channelHandlerContext.close();
        }
    }

    private void sendDataWrite(byte[] bytes, int i) {
        final ByteBuf buf = channelHandlerContext.alloc().heapBuffer(i);
        byte[] sendBytes = new byte[i];
        System.arraycopy(bytes, 0, sendBytes, 0, i);
        buf.writeBytes(sendBytes);
        channelHandlerContext.writeAndFlush(buf);
    }

    public void channelSendDataHead() {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "video/x-flv");
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");

        //允许跨域访问
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT,DELETE");
        channelHandlerContext.writeAndFlush(response);
    }

    public void channelDownloadDataHead(String fileName) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/octet-stream; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
        try {
            response.headers().add(HttpHeaderNames.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\";");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //允许跨域访问
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Accept");
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT,DELETE");
        channelHandlerContext.writeAndFlush(response);
    }
}
